import { Injectable,Inject } from '@angular/core';
import {HttpClient,HttpHeaders} from "@angular/common/http";
import {User,Project,Auth} from "../domain"
import {Observable,from,of} from "rxjs";
import {map,mergeMap,count,switchMap,mapTo,filter,reduce} from "rxjs/operators";
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private readonly domain = 'users';
  private headers = new HttpHeaders({
    'content-Type':'application/json'
  });
  private token = 'dfdgfjiojifdsfijdojjiojioj';
  constructor(private http:HttpClient,@Inject('BASE_CONFIG') private config) { }
  register(user:User):Observable<any>{
    const uri = `${this.config.uri}/${this.domain}`;
    return this.http.get(uri,{params:{'email':user.email}}).pipe(
      switchMap(res=>{
        if(res['length']>0){
          throw new Error('user existed');
        }
        return this.http.post(uri,JSON.stringify(user),{headers:this.headers}).pipe(
          map(r=>({token:this.token,user:r}))
        )
      })
    )
  }
  login(username:string,password:string):Observable<any>{
    const uri = `${this.config.uri}/${this.domain}`;
    return this.http.get(uri,{params:{'email':username,'password':password}}).pipe(
      map(res=>{
        if(res['length']===0){
          throw 'username or password not match';
        }
        return {
          token: this.token,
          user: res[0]
         }
      })
    )
  }

}
